# 部署脚本 - PowerShell版本，用于部署前后端到nginx反向代理

# 配置变量
$PROJECT_DIR = "d:\src\openmonitor"  # 项目根目录
$NGINX_CONFIG = "C:\nginx\conf\openmonitor.conf"  # nginx配置文件路径，根据实际路径修改
$DIST_DIR = "$PROJECT_DIR\web\dist"  # 前端构建产物目录
$BACKEND_DIR = "$PROJECT_DIR\backend"  # 后端目录
$LOG_DIR = "d:\logs\openmonitor"  # 日志目录

# 创建日志目录
if (!(Test-Path $LOG_DIR)) {
    New-Item -ItemType Directory -Path $LOG_DIR -Force
}

Write-Host "=== 开始部署金融监控系统 ===" -ForegroundColor Green

# 1. 构建前端
Write-Host "1. 构建前端代码..." -ForegroundColor Yellow
Set-Location $PROJECT_DIR\web
npm run build:nginx
if ($LASTEXITCODE -ne 0) {
    Write-Host "前端构建失败！" -ForegroundColor Red
    exit 1
}
Write-Host "前端构建成功！" -ForegroundColor Green

# 2. 检查后端是否运行
Write-Host "2. 检查后端服务状态..." -ForegroundColor Yellow
$backendProcess = Get-Process -Name "python" -ErrorAction SilentlyContinue | Where-Object {$_.MainWindowTitle -like "*uvicorn*"}
if ($backendProcess) {
    Write-Host "发现后端服务正在运行，停止服务..." -ForegroundColor Yellow
    $backendProcess.Kill()
    Start-Sleep -Seconds 3
}

# 3. 启动后端服务
Write-Host "3. 启动后端服务..." -ForegroundColor Yellow
Set-Location $BACKEND_DIR
$backendLog = "$LOG_DIR\backend.log"
Start-Process -FilePath "python" -ArgumentList "-m uvicorn app.main:app --host 0.0.0.0 --port 10001" -NoNewWindow -RedirectStandardOutput $backendLog -RedirectStandardError $backendLog
Write-Host "后端服务已启动" -ForegroundColor Green

# 4. 更新nginx配置
Write-Host "4. 更新nginx配置..." -ForegroundColor Yellow
# 复制nginx配置文件
Copy-Item "$PROJECT_DIR\nginx-deploy.conf" $NGINX_CONFIG -Force
# 更新配置中的路径
$configContent = Get-Content $NGINX_CONFIG
$configContent = $configContent -replace '/path/to/openmonitor/web/dist', ($DIST_DIR -replace '\\', '/')
$configContent | Set-Content $NGINX_CONFIG

# 5. 测试nginx配置并重启
Write-Host "5. 测试nginx配置..." -ForegroundColor Yellow
$nginxPath = "C:\nginx\nginx.exe"  # 根据实际nginx安装路径修改
$nginxTest = & $nginxPath -t 2>&1
if ($LASTEXITCODE -eq 0) {
    Write-Host "nginx配置测试通过，重启nginx..." -ForegroundColor Green
    & $nginxPath -s reload
    Write-Host "nginx已重启" -ForegroundColor Green
} else {
    Write-Host "nginx配置测试失败，请检查配置！" -ForegroundColor Red
    Write-Host $nginxTest -ForegroundColor Red
    exit 1
}

Write-Host "=== 部署完成 ===" -ForegroundColor Green
Write-Host "前端访问地址: http://www.bytech.top:8081/monitor" -ForegroundColor Cyan
Write-Host "后端API地址: http://www.bytech.top:8081/api" -ForegroundColor Cyan
Write-Host "后端日志: $backendLog" -ForegroundColor Cyan